package thread.semaphore;

import java.util.Random;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Semaphore;

/**
 * Created by 4790K_NSL on 2017/4/25.
 */
public class SemaphoreDemo {

    public static void main(String[] args) {
        final Semaphore semaphore=new Semaphore(3);
        ExecutorService service= Executors.newCachedThreadPool();
        for (int i = 0; i < 10; i++) {
            Runnable runalbe=new Runnable() {
                @Override
                public void run() {

                    try {
                        semaphore.acquire();
                        System.out.println("线程" + Thread.currentThread().getName() +
                                "进入，当前已有" + (3-semaphore.availablePermits()) + "个并发");
                        Thread.sleep(new Random().nextInt(1000));
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    System.out.println("线程" + Thread.currentThread().getName() +
                            "即将离开");
                    semaphore.release();
                    System.out.println("线程" + Thread.currentThread().getName() +
                            "已离开，当前已有" + (3-semaphore.availablePermits()) + "个并发");
                }
            };

            service.execute(runalbe);
        }
    }
}
